var consts;

function draw() {

    dataSource =  new YAHOO.util.LocalDataSource(data);
    var myAutoComp = new YAHOO.widget.AutoComplete("courseInput","autocomplete",dataSource);
    myAutoComp.queryMatchContains = true;
    myAutoComp.queryDelay = 0.01;
    myAutoComp.forceSelection = true;
    myAutoComp.maxResultsDisplayed = 20;
    myAutoComp.formatResult = function(oResultData, sQuery, sResultMatch) {
	return sResultMatch.split(sQuery.toUpperCase()).join("<b>"+sQuery.toUpperCase()+"</b>");
   
    };

    $('#hide').hide();
    $('#right').hide();
    $('#schedule').hide();
    $('#classContainer').hide('slow');
    $('#controls').hide();
    var canvas = document.getElementById("canvas");  
    if (canvas.getContext) { 
        var ctx = canvas.getContext("2d");  
		
	var my_gradient = ctx.createLinearGradient(canvas.height, canvas.width,0,0 );
	my_gradient.addColorStop(0, "white");
	my_gradient.addColorStop(1, "rgb(200,200,200)");
 
	ctx.fillStyle = my_gradient;
 
	ctx.fillRect(0, 0, canvas.width, canvas.height);
	document.getElementById('courseInput').style.color = "gray"
	    }  
	//make sliders
    var days= new Array("m","t","w","th","f");
    if(document.all){
	for(var i=0;i<5;i++){	eval('$("#'+days[i]+'slider").slider({range: true,min: 800,max: 2000,step: 50,values: [ 800, 2000 ],slide: function( event, ui ) {$("#'+days[i]+'slider").children()[1].innerText = "start:" + (ui.values[0]%100==0)? (ui.values[0]-100)%1200+100 : (ui.values[0]-20-100)%1200+100;$("#'+days[i]+'slider").children()[2].innerText = (ui.values[1]%100==0)? (ui.values[1]-100)%1200+100 : (ui.values[1]-20-100)%1200+100 ;}});');
	$('#'+days[i]+'slider').children()[1].innerText="800";
	$('#'+days[i]+'slider').children()[2].innerText="800";
        } 
    } else{
	for(var i=0;i<5;i++){	eval('$("#'+days[i]+'slider").slider({range: true,min: 800,max: 2000,step: 50,values: [ 800, 2000 ],slide: function( event, ui ) {$("#'+days[i]+'slider").children()[1].textContent = "start:" + (ui.values[0]%100==0)? (ui.values[0]-100)%1200+100 : (ui.values[0]-20-100)%1200+100;$("#'+days[i]+'slider").children()[2].textContent = (ui.values[1]%100==0)? (ui.values[1]-100)%1200+100 : (ui.values[1]-20-100)%1200+100 ;}});');
	$('#'+days[i]+'slider').children()[1].textContent="800";
	$('#'+days[i]+'slider').children()[2].textContent="800";
        } 
    }
	
}

function addOrdering() {
//make sure you cant add the same ordering config twice
//make sure you dont try to add one ordering, and the inverse

	var X = document.getElementById('x').value;
	var Y = document.getElementById('y').value;
		
		
	if(X!=Y &&  $('div:contains('+X+' before '+Y+')').length==0 &&  $('div:contains('+Y+' before '+X+')').length==0){
		var tag = document.createElement("Bf");
		tag.innerHTML = '<div id="tag" onclick="$(this).hide(200, function () { $(this).parent().remove();  });"> '+X+' before '+Y+'</div>';
		document.getElementById("selectedC").appendChild(tag);
		//dynamic evaluationg		
		evaluate();			
	}
}
function addXoY() {
	var x = document.getElementById('totalclasses').value;

	if(x!='X' &&  $('div:contains( Allow only '+x+' out of the selected classes )').length==0){
		///ADD X OR Y FUNCTION
		var tag = document.createElement("XOY");
		tag.innerHTML = '<div id="tag" onClick="$(this).hide(200, function () { $(this).parent().remove();  });"> Allow only '+x+' out of the selected classes </div>';
		document.getElementById("selectedC").appendChild(tag);
	}
}
function btb() {
	if( $('div:contains( Allow only back to back events )').length==0){
		var tag = document.createElement("BTB");
		tag.innerHTML = '<div id="tag" onClick="$(this).hide(200, function () { $(this).parent().remove();  });"> Allow only back to back events </div>';
		document.getElementById("selectedC").appendChild(tag);
		//dynamic evaluationg		
		evaluate();
	}
}
function maxtime() {
	var day = document.getElementById('dayofweek').value;
	var time = document.getElementById('max').value;
	if( $('div:contains( No more than '+time+' hour(s) on '+day+')').length==0 && time!=0 && "0123456789".indexOf(time)!=-1 && "abcdefghijklmnopqrstuvwxyz".indexOf(time)==-1){
		var tag = document.createElement("N");
		tag.innerHTML = '<div id="tag" onClick="$(this).hide(200, function () { $(this).parent().remove();  });"> No more than '+time+' hour(s) on '+day+'</div>';
		document.getElementById("selectedC").appendChild(tag);
		//dynamic evaluationg		
		evaluate();
	}
}
function addTime(day) {
	var start = $( "#"+day+"slider" ).slider( "option", "values" )[0];
	var finish =$( "#"+day+"slider" ).slider( "option", "values" )[1];
	
	if( $('div:contains( no classes on '+day+' from '+start+' to '+ finish+')').length==0){
		var tag = document.createElement("RTD");
		tag.innerHTML =  '<div id="tag" onclick="$(this).hide(200, function () { $(this).parent().remove();  });"> no classes on '+day+' from '+start+' to '+ finish+'</div>';
		document.getElementById("selectedC").appendChild(tag);
		//dynamic evaluation		
		evaluate();
	}
}
function lockId() {
	var ID = document.getElementById('id').value;
	if(ID!="" && $('div:contains( Lock '+ID+' )').length==0){
		var tag = document.createElement("LOCK");
		tag.innerHTML = '<div id="tag" onclick="$(this).hide(200, function () { $(this).parent().remove();  });"> Lock '+ID+' </div>';
		document.getElementById("selectedC").appendChild(tag);
		evaluate();
	}
}
function addclass() {
    var classname = document.getElementById('courseInput').value;
	    if(classname !="" &&classname !=document.getElementById('courseInput').defaultValue && $.inArray(classname, data)!=-1){
		var tag = document.createElement("class");
		tag.innerHTML = '<div id="tag" onclick="$(this).hide(200, function () { $(this).parent().remove(); populateSelects();  });"> '+classname+' </div>';
		document.getElementById('classes').appendChild(tag);
		document.getElementById('courseInput').value = "";
		populateSelects();
		populateXOY()
		//dynamic evaluation
		evaluate();
	    }
 
}
function addevent() {
//this needs to get the event name and information to send as a query
	var eventname = document.getElementById('eventinput').value;
	var info = document.getElementById('occurenceinfo').value;
	if(info !="" && info != document.getElementById('occurenceinfo').defaultValue){
		var tag = document.createElement("event");
		tag.innerHTML = '<div id="tag" onclick="$(this).hide(200, function () { $(this).parent().remove(); });"> ' + eventname + '-' +info + ' </div>';
		document.getElementById('classes').appendChild(tag);
		//document.getElementById('occurenceinfo').value = "";
		//populateSelects();
		//populateXOY()
		//dynamic eval
		//evaluate();
	}
}
function populateSelects(){
    var classes=document.getElementById('classes');
    var l = classes.childElementCount;
    document.getElementById("x").options.length = l-7;
    document.getElementById("y").options.length = l-7;
    if(l==7){
	document.getElementById("x").options[0]=new Option("no classes selected","");
	document.getElementById("y").options[0]=new Option("no classes selected","");}
    for(var i =7;i<l;i++){
	if(document.all){
		document.getElementById("x").options[i-7]=new Option(classes.children[i].innerText,classes.children[i].innerText);
		document.getElementById("y").options[i-7]=new Option(classes.children[i].innerText,classes.children[i].innerText);
    	} else{
		document.getElementById("x").options[i-7]=new Option(classes.children[i].textContent,classes.children[i].textContent);
		document.getElementById("y").options[i-7]=new Option(classes.children[i].textContent,classes.children[i].textContent);
	}
    }
	
}
function populateXOY(){
	var classes=document.getElementById('classes');
   	var l = classes.childElementCount;
	document.getElementById("totalclasses").options.length = l-7;
	for(var i=7; i<l; i++){
		document.getElementById("totalclasses").options[i-7] = new Option(""+(i-6));
	}
}

function clearText(thefield){
    if (thefield.defaultValue==thefield.value){
	thefield.value = ""
	    thefield.style.color = "black";
    }
}

var numClasses=0;
var validResponse=false;
function submit(){
//GET RID OF TWO EXTRA SPACES

//this needs an $.inArray(classname, data) if statement to make sure you only add university classes
    events= "";
    classList = "";
    classes = document.getElementById("classes");
		//get the first element 
		classcheck = classes.children[16].textContent.trim();
		
		if($.inArray(classcheck, data)!=-1){classList+=classes.children[16].textContent;}
		else{events+=classes.children[16].textContent;}
		//get the rest. in both cases, we check to see if the current element is a class or an event
		for(var i =17;i<classes.childElementCount;i++){
		      classcheck = classes.children[i].textContent.trim();      
		      if($.inArray(classcheck, data)!=-1){classList+=",,"+classes.children[i].textContent;}
		      else{ events+= ",," + classes.children[i].textContent;}			
		}

	//get rid of leaading ",,"
	if(events.charAt(0)==','){events=events.substring(2);}
	if(classList.charAt(0)==','){classList=classList.substring(2);}

    document.getElementById("controls").innerHTML= "<h3>loading</h3>";
    consts=generateConstraints();
    
    //$.get("test.py", {classes:classList, constraints:consts}, function (response){ document.getElementById("controls").innerHTML=(response); var data=response.split(","); drawAllClasses(data);});
	
    xmlhttpPost("/cgi-bin/NTFTRunner/solve.py");
	

}
//this function is the start of work on making the scheduler dynamic. (update upon addition of any class or constraint) this isn't efficient yet, it regenerates EVERYTHING everytime something changes.
function evaluate(){
//this is the same as submit, but is needed to diffentiate from posting results and jut computing in the background.

    events= "";
    classList = "";
    classes = document.getElementById("classes");

	//get the first element 
	classcheck = classes.children[16].textContent.trim();
	
	if($.inArray(classcheck, data)!=-1){classList+=classes.children[16].textContent;}
	else{events+=classes.children[16].textContent;}
	//get the rest. in both cases, we check to see if the current element is a class or an event
	for(var i =17;i<classes.childElementCount;i++){
	      classcheck = classes.children[i].textContent.trim();      
	      if($.inArray(classcheck, data)!=-1){classList+=",,"+classes.children[i].textContent;}
	      else{ events+= ",," + classes.children[i].textContent;}			
	}
	
	//get rid of leaading ",,"
	if(events.charAt(0)==','){events=events.substring(2);}
	if(classList.charAt(0)==','){classList=classList.substring(2);}

    document.getElementById("controls").innerHTML= "<h3>loading</h3>";
    consts=generateConstraints();
    xmlhttpPostEval("/cgi-bin/NTFTRunner/solve.py");
}
function xmlhttpPostEval(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
   self.xmlHttpReq.setRequestHeader('Content-Type', 'text');
    self.xmlHttpReq.onreadystatechange = function() {
      if (self.xmlHttpReq.readyState == 4) {
		
		response =self.xmlHttpReq.responseText;


		if(response.indexOf("[]")==-1){
			numClass=0;
			document.getElementById("classContainer").innerHTML = "";
			document.getElementById("controls").innerHTML = response;
			response=response.substring(response.indexOf("["));
			response=response.split("][");
			for(i in response){
				response[i]=response[i].replace(']','').replace('[','').split(") ,(")
				for(j in response[i]){
					response[i][j]=response[i][j].replace(')','').replace('(','').split(",")
				}
			}
		  
	        }
		else{
			alert("There are no possible schedules with the inputs given. Try removing your most recent addition");
		}
      }
    }
    self.xmlHttpReq.send(getquerystring());
	
}

function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'text');
    self.xmlHttpReq.onreadystatechange = function() {
      if (self.xmlHttpReq.readyState == 4) {
		
		response =self.xmlHttpReq.responseText;
		

		if(response.indexOf("[]")==-1){
		
		numClass=0;
		document.getElementById("classContainer").innerHTML = "";
		document.getElementById("controls").innerHTML = response;
		response=response.substring(response.indexOf("["));
		response=response.split("][");
		for(i in response){
			response[i]=response[i].replace(']','').replace('[','').split(") ,(")
			for(j in response[i]){
				response[i][j]=response[i][j].replace(')','').replace('(','').split(",")
			}
		}
		    $('#submitbutton').hide('slow');
		    $('#classes').hide('slow');
		    $('#left').hide('slow');
		    $('#classContainer').show("slow");
		    $('#right').show('slow');	
		    $('#hide').show('slow');
		    $('#schedule').show('slow');
		    $('#controls').show('slow');	
		     drawSchedule();
		drawAllClasses(numClass);
		}
		else{
	alert("schedule has no valid answer sets given constraints, or we fucked something up. please try again we are really sorry seriously. maybe that one class doesn't even exist and we lied to you.");
		}
      }
    }
    self.xmlHttpReq.send(getquerystring());
	
}

function getquerystring() {
	qstr = "class="+classList+"&consts="+consts+"&events="+events;
	return qstr;
}
function generateConstraints(){
c=Array();

var rtds= $("RTD");
	for(i in rtds){
		var s;
		//if(document.all){s =rtds[i].innerText;}
		//else{s =rtds[i].textContent;}
		s = rtds[i].textContent;
		if(s!=undefined){
			//....yeaaah we're not even sure what's going on here it's 4:30 am and we've been drinking a bit
			day=s.substring(s.indexOf("on")+3).split(" ");
			if(day[2]!=undefined)
			c.push("RTD " + day[0] +" "+ day[2] +" "+ day[4] );
		}
	}

var bs= $("Bf");
	for(j in bs){
		var s = bs[j].textContent;//text Content has some subtle differences man.
		if(s!=undefined){	
			//look for lowercase "before" if uppercase, you can accidentally split in the middle of a class name	
			var b = s.split("before");
			
			var class1= b[0].replace(new RegExp("[^A-Za-z0-9]",'g'),"").toLowerCase();
			var class2= b[1].replace(new RegExp("[^A-Za-z0-9]",'g'),"").toLowerCase();
			c.push("B " + class1 + " " + class2);
			
		}
	}

var btb = $("BTB")
		//var s = btb[0].innerText;
		if(btb[0]!=undefined){
			c.push("BTB");
		}

var mt = $("N")
	for(j in mt){
		var s;
		//if(document.all){ s = mt[j].innerText;}
		//else{s = mt[j].textContent;}		
		s = mt[j].textContent;		
		if(s!=undefined){
			//skip the unimportant letters of the display and scrape what you need at posistions 3 and 6
			var list = s.split(" ");
			var time = list[4];
			var day = list[7];
			//now we format the time and day into a way clingo will be able to use it. By this point, incorrect input as been prevented. time is a integer and day is the full word of a day. "Monday"
			time = time * 100;
			day = day.substring(0,2).toLowerCase();
			if( day.indexOf("th") == -1)
				day = ""+day.charAt(0);
			c.push("N "+time+" "+day);
		}

	} 

var xoy = $("XOY")
	for(j in xoy){
		var s = xoy[j].textContent;
		if(s!=undefined){
			var x = s.substring(s.indexOf("only ")+4,s.indexOf(" out"));
			c.push("XOY"+x);	
		}
	}

var lock = $("LOCK")
	for(j in lock){
		var s;
		s= lock[j].textContent;
		if(s!=undefined){
			var ID = s.substring(s.indexOf("LOCK ")+6);
			c.push("LOCK"+ID);
		}
	}


//return the array as a string joined together by commas!
return c.join(",");
}

function sho(){
    $('#classes').show('slow');
    $('#left').show('slow');
    $('#hide').hide('slow');
    $('#right').hide();
    $('#schedule').hide('slow');
    $('#classContainer').hide('slow');
    $('#controls').hide('slow');
    $('#submitbutton').show('slow');
} 


